# @Time : 2021/3/5 17:29
# @Author : Fioman 
# @Phone : 13149920693

"""
主要是用来操作数据库的类
"""
from timeit import default_timer

import pymysql

host = "localhost"
port = 3306
db = "mysql"
user = "root"
password = "123456"


def get_connection():
    conn = pymysql.connect(host=host, port=port, db=db, user=user, password=password)
    return conn


class MysqlManager(object):
    def __init__(self, commit=True,logTime = True,logLabel="总用时"):
        """
        :param commit:是否最后提交事务(设置为False的时候方便单元测试)
        :param logTime: 是否打印程序运行总时间
        :param logLabel: 自定义log的文字
        """
        self._commit = commit
        self._logTime = logTime
        self._logLabel = logLabel

    def __enter__(self):
        # 如果需要记录时间
        if self._logTime:
            self._start = default_timer()

        # 在进入的时候自动后去连接和cursor
        conn = get_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        conn.autocommit = False

        self._conn = conn
        self._cursor = cursor
        return self

    def __exit__(self, *excInfo):
        # 提交事务
        if self._commit:
            self._conn.commit()

        # 在退出的时候自动关闭连接
        self._cursor.close()
        self._conn.close()

        if self._logTime:
            timeUsed = default_timer() - self._start
            print("-- {} : {:.2f} 秒".format(self._logLabel,timeUsed))

    # 加了property之后,可以用调用属性的方式来调用方法,所以这里是可以搞定的.
    @property
    def cursor(self):
        return self._cursor

if __name__ == '__main__':
    mysql = MysqlManager()
    with mysql as sq:
        sq.cursor.execute("select * from User")
        data = sq.cursor.fetchone()
        print(data)

    with mysql as sql:
        sq.cursor.execute("select * from User")
        data = sq.cursor.fetchone()
        print(data)


